<template>
  <basic-container>
    <avue-crud :option="option"
               v-model:search="search"
               v-model:page="page"
               v-model="form"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @sort-change="sortChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   icon="el-icon-delete"
                   effect="dark"
                   v-if="permission.proxy_platform_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-divider direction="vertical" />
      </template>

      <template #menu-btn="scope">
        <el-dropdown-item divided icon="el-icon-setting" @click.stop="handleDataSub(scope.row)">配 置</el-dropdown-item>
        <el-dropdown-item v-if="scope.row.viewWhitelistApi" icon="el-icon-view" @click.stop="handleApi(scope.row,'view')">查看白名单</el-dropdown-item>
        <el-dropdown-item v-if="scope.row.addWhitelistApi" icon="el-icon-circle-plus-filled" @click.stop="handleApi(scope.row,'add')">添加白名单</el-dropdown-item>
        <el-dropdown-item v-if="scope.row.delWhitelistApi" icon="el-icon-remove-filled" @click.stop="handleApi(scope.row,'del')">删除白名单</el-dropdown-item>
      </template>

      <template #website="{ row }">
        <el-link type="primary" :href="row.website" target="_blank">{{ row.website }}</el-link>
      </template>
      <template #status="{ row }">
        <el-tag :type="type.enable_disable[row.status]" effect="dark">{{ row.$status }}</el-tag>
      </template>
      <template #info="{ row }">
        <el-text v-if="row.info" size="small">{{ row.info }}</el-text>
        <el-divider v-if="row.infoApi" direction="vertical" />
        <el-button v-if="row.infoApi" :loading="infoLoading" type="danger" size="small" link @click="handleApi(row,'info')">查询</el-button>
      </template>
    </avue-crud>

    <el-dialog
      v-model="configBox"
      append-to-body
      destroy-on-close
      title="配置"
      width="80%"
      :align-center="true">
      <config ref="configRef" :proxyPlatformId="proxyPlatformId"></config>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, api } from '@/api/proxy/platform';
import option from '@/option/proxy/platform';
import config from '@/views/proxy/config.vue';
import { mapGetters } from 'vuex';
import func from '@/utils/func';
import type from '@/const/tag/type';

export default {
  data() {
    return {
      configBox: false,
      infoLoading: false,
      proxyPlatformId: undefined,
      form: {},
      query: {},
      sort: {},
      search: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: [],
      jsonReadonly: true
    };
  },
  components: {
    config
  },
  computed: {
    type() {
      return type;
    },
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.proxy_platform_add, false),
        viewBtn: this.validData(this.permission.proxy_platform_view, false),
        delBtn: this.validData(this.permission.proxy_platform_delete, false),
        editBtn: this.validData(this.permission.proxy_platform_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  created() {
    this.sort.ascs = 'sorting';
  },
  methods: {
    rowSave(row, done, loading) {
      func.jsonCompress(row, 'Api');
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      func.jsonCompress(row, 'Api');
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      func.isReadonly(this.option.column, 'Api', ['view'].includes(type));
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    sortChange(val) {
      this.sort = {};
      if (func.notEmpty(val.order)) {
        if (val.order === 'ascending') {
          this.sort.ascs = func.cameCaseToLine(val.prop);
        } else {
          this.sort.descs = func.cameCaseToLine(val.prop);
        }
      }
      this.refreshChange();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        status
      } = Object.assign(params, this.query);

      let values = {
        status_equal: status
      };

      getList(page.currentPage, page.pageSize, this.sort, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleDataSub(row) {
      this.proxyPlatformId = row.id;
      this.configBox = true;
      this.$nextTick(() => {
        let column = this.findObject(this.$refs.configRef.option.column, 'proxyPlatformId');
        column.value = this.proxyPlatformId;
        column.disabled = true;
        column.search = false;
      });
    },
    handleApi(row, type) {
      let data = { id: row.id, type: type };
      let title = '';
      switch (type) {
        case 'view':
          title = '查看白名单';
          break;
        case 'add':
          title = '添加白名单';
          break;
        case 'del':
          title = '删除白名单';
          break;
      }
      if (type === 'info') {
        const loading = this.$loading({
          lock: true,
          text: '请求中,请稍后...',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        api(data).then(res => {
          loading.close();
          row.info = res.data.data;
        }).finally(() => {
          loading.close();
        });
      } else {
        if (type !== 'view') {
          this.$prompt(type === 'del' && row.platform === 'smartdaili' ? '请查看白名单获取ID,请输入ID' : '请输入IP', title, {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          }).then(({ value }) => {
            const loading = this.$loading({
              lock: true,
              text: '请求中,请稍后...',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            if (type === 'add' && row.platform === 'smartdaili') {
              data.ips = value.split(',');
            } else {
              data.ip = value;
            }
            api(data).then(res => {
              loading.close();
              let message = '';
              try {
                message = JSON.parse(res.data.data);
              } catch (e) {
                message = res.data.data;
              }
              this.$notify({
                title: title,
                message: message,
                type: 'success',
                duration: 30000
              });
            }).finally(() => {
              loading.close();
            });
          });
        } else {
          const loading = this.$loading({
            lock: true,
            text: '请求中,请稍后...',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          api(data).then(res => {
            loading.close();
            let message = '';
            try {
              message = JSON.parse(res.data.data);
            } catch (e) {
              message = res.data.data;
            }
            this.$notify({
              title: title,
              message: message,
              type: 'success',
              duration: 30000
            });
          }).finally(() => {
            loading.close();
          });
        }
      }
    }
  }
};
</script>

<style>
</style>
